/**
 *	主服务端
 *	开发者：雨中磐石
 *	地址：www.rockoa.com
 *	日期：2023-07-19
 */

package com.framerock.server;



import com.framerock.baselib.CLog;
import com.framerock.baselib.Config;
import com.framerock.baselib.Rock;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class HttpServer{

    /*
    * 限制的请求
    * */
    public static String web_origin;

    private static ServerSocket serverSocket;

    private static boolean openbool = true;

    /**
     * 客户端链接的数量
     * */
    private static int clientCount  = 0;


    /**
     * 启动服务
     * */
    public static void start()
    {
        new Thread(new Runnable() {
            @Override
            public void run() {
                startSocket();
            }
        }).start();
    }

    /*
    * 停止服务
    * */
    public static void stop()
    {
        openbool = false;
        try {
            if(serverSocket != null)serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        WebSocketClient.closeAll();
        serverSocket = null;
        TaskServer.stop();
    }

    /**
     * 启动webserver服务
     * */
    private static void startSocket() {
        String port = Config.getConfig("web.port", "8089");
        web_origin  = Config.getConfig("web.origin");
        try {
            String host  = Config.getConfig("web.host", "0.0.0.0");
            serverSocket = new ServerSocket(Integer.parseInt(port), 50, InetAddress.getByName(host));
            CLog.print("[pid:"+Rock.getProcessId()+"]---httpserver http://127.0.0.1:" + port + " runing ---");
            while (openbool) {
                Socket socket = serverSocket.accept();
               // if (socket != null)serviceLink(socket, null);
                if (socket != null)new myThrend(socket).start();
            }
        } catch (IOException e) {
            String errstr = e.toString();
            if(Rock.contain(errstr, "Address already in use")) {
                CLog.error("error:" + errstr + " --port(" + port + ")is exist--");
            }
            stop();
        }
    }

    /**
     * 获取服务的链接
     * */
    public static String getHost()
    {
        String port = Config.getConfig("web.port", "8089");
        String host = Config.getConfig("web.host", "127.0.0.1");
        return "http://"+host+":"+port+"/";
    }

    /**
     * 线程
     * */
    private static class myThrend extends Thread{
        private Socket socket;
        public myThrend(Socket socket){
            this.socket = socket;
        }
        @Override
        public void run() {
            serviceLink(socket, this);
        }
    }

    /**
     * 线程池用的
     * */
    private static class myRunnable implements Runnable {
        private HttpClient client;
        public myRunnable(HttpClient clien){
            client = clien;
        }
        @Override
        public void run() {
            serviceClient(client);
        }
    }

    /**
     * 有客户端请求处理
     * */
    private static void serviceLink(Socket socket, Thread thread)
    {
        clientCount ++;
        HttpClient client   = new HttpClient(socket);
        client.nowThread    = thread;
        client.nowCount     = clientCount + 0;
        String origin       = client.getOrigin();
        //验证来源对不对
        if(!Rock.isEmpt(web_origin) && !Rock.contain(web_origin, "*") && !Rock.contain(web_origin, origin)) {
            client.showHttp(500, "from("+origin+")origin error");
            client.close();
            return;
        }
        serviceClient(client);//开启处理请求
    }

    /**
     * 有客户端请求处理
     * */
    private static void serviceClient(HttpClient client)
    {
        String body         = "";
        int code            = 200;
        String path = client.getPath();
        //websocket服务端的请求
        if(path.indexOf("/websocket")==0) {
            String Upgrade = client.getHeader("Upgrade");
            if (Rock.isEmpt(Upgrade)) {
                body = "websocket not found Upgrade";
                client.showHttp(code, body);
                client.close();
            } else {
                HttpWebSocket websocet = new HttpWebSocket(client);
                body = websocet.getSocketbody();
                client.writeResponse(body); //发送接受握手
                websocet.startRun();
            }
        }else if(path.indexOf(".")>0){ //静态文件读取
            HttpStatic httpatatic = new HttpStatic(client);
            httpatatic.writeBody(path);
            client.close();
        }else {
            try {
                body = HttpController.getControllerBody(client); //去控制器请求数据
            } catch (Exception e) {
                e.printStackTrace();
                body = e.toString();
                code = 500;
            }
            String method       = client.getMethod();
            if(method.equals("SOCKET") || method.equals("SOCKETPOST")){
                client.writeResponse(body);
            }else {
                client.showHttp(code, body);
            }
            client.close();
        }
    }
}